package com.project.hqshorttaxi.controller;

import com.github.pagehelper.PageHelper;
import com.project.hqshorttaxi.aop.TagLog;
import com.project.hqshorttaxi.dto.ShortDistanceParam;
import com.project.hqshorttaxi.dto.WhiteListInputParam;
import com.project.hqshorttaxi.entity.*;
import com.project.hqshorttaxi.service.*;
import com.project.hqshorttaxi.util.ExcelUtil;
import com.project.hqshorttaxi.util.PageInfo;
import com.project.hqshorttaxi.util.RestResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/whitelistInput/")
public class WhiteListInputController {

    @Resource
    WhiteListInputService whiteListInputService;
    @Resource
    WhiteListService whiteListService;
    @Resource
    ShortDistanceService shortDistanceService;
    @Resource
    LoginService loginService;
    @Resource
    SettingService settingService;

    /**
     * 列表
     */
    @PostMapping("page")
    @TagLog(operation = 0, content = "查询白名单导入列表")
    public RestResult page(@RequestBody WhiteListInputParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        return RestResult.ok(new PageInfo<>(whiteListInputService.list(param)));
    }

    /**
     * 根据ID获取
     */
    @GetMapping("{id}")
    @TagLog(operation = 0, content = "根据ID获取白名单导入详细信息")
    public RestResult pageById(@PathVariable Integer id) {
        return RestResult.ok(whiteListInputService.getById(id));
    }


    /**
     * 导入
     */
    @PostMapping("upload")
    @TagLog(operation = 6, content = "白名单导入文件")
    public RestResult upload(@RequestHeader(value = "authorization") String token, MultipartFile file) {
        try {
            Login login = loginService.getByToken(token);
            if (login == null) {
                return RestResult.error("用户不存在");
            }
            List<List<String>> list = ExcelUtil.getExcelData(file, true);
            if (list.size() == 0) {
                return RestResult.error("导入的文件数据至少有一行");
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate now = LocalDate.parse(sdf2.format(new Date()), formatter);
            List<WhiteListInput> whiteListInputDtos = new ArrayList<WhiteListInput>();
            for (int i = 0; i < list.size(); i++) {
//                if (list.get(i).size() != 6) {
//                    return RestResult.error("第" + (i + 1) + "行，数据有空值");
//                }
                WhiteListInput dto = new WhiteListInput();
//                if (StringUtils.isEmpty(list.get(i).get(0))) {
//                    return RestResult.error("第" + (i + 1) + "行，车牌号不能为空");
//                }
                if(!StringUtils.isEmpty(list.get(i).get(0))) {
                    dto.setPlateNumber(list.get(i).get(0));
//                if (StringUtils.isEmpty(list.get(i).get(1))) {
//                    return RestResult.error("第" + (i + 1) + "行，被拒绝时间不能为空");
//                }
//                dto.setRejectTime(sdf.parse(list.get(i).get(1)));
//                dto.setRejectDate(sdf2.format(sdf.parse(list.get(i).get(1))));
//                if (StringUtils.isEmpty(list.get(i).get(2))) {
//                    return RestResult.error("第" + (i + 1) + "行，被拒绝原因不能为空");
//                }
//                dto.setRefuse(list.get(i).get(2));
//                if (StringUtils.isEmpty(list.get(i).get(3))) {
//                    return RestResult.error("第" + (i + 1) + "行，遗漏订单开始时间不能为空");
//                }
//                dto.setOrderBeginTime(sdf.parse(list.get(i).get(3)));
//                if (StringUtils.isEmpty(list.get(i).get(4))) {
//                    return RestResult.error("第" + (i + 1) + "行，遗漏订单结束时间不能为空");
//                }
//                dto.setOrderEndTime(sdf.parse(list.get(i).get(4)));
//                if (StringUtils.isEmpty(list.get(i).get(5))) {
//                    return RestResult.error("第" + (i + 1) + "行，订单里程不能为空");
//                }
//                dto.setOrderMileage(Double.parseDouble(list.get(i).get(5)));
                    dto.setCreateUser(login.getUserName());
                    dto.setUpdateUser(login.getUserName());
                    dto.setCreateTime(new Date());
                    dto.setUpdateTime(new Date());
                    dto.setStatus(1);
                    whiteListInputDtos.add(dto);
                }
            }
//            List<Setting> settingList = settingService.list();
//            if (settingList.size() == 0) {
//                return RestResult.error("基础参数未设置");
//            }
//            if (settingList.get(0).getBeforeOrderTimeLimit() == null || settingList.get(0).getAfterOrderTimeLimit() == null || settingList.get(0).getOrderDistanceLimit() == null) {
//                return RestResult.error("基础参数未设置");
//            }
//            // 去除重复值，车牌号和被拒绝日期分组
//            Map<String, Map<String, List<WhiteListInput>>> groupMap = whiteListInputDtos.stream().collect(Collectors.groupingBy(WhiteListInput::getPlateNumber, Collectors.groupingBy(WhiteListInput::getRejectDate)));
//            for (Map.Entry<String, Map<String, List<WhiteListInput>>> entry : groupMap.entrySet()) {
//                Map<String, List<WhiteListInput>> valueMap = entry.getValue();
//                for (Map.Entry<String, List<WhiteListInput>> entry2 : valueMap.entrySet()) {
//                    List<WhiteListInput> listInputDtos = entry2.getValue();
//                    for (int i = 1; i < listInputDtos.size(); i++) {
//                        listInputDtos.get(i).setStatus(0);
//                    }
//                }
//            }
//            List<WhiteListInput> filterList = whiteListInputDtos.stream().filter(item -> item.getStatus() == null).collect(Collectors.toList());
//            if (filterList.size() > 0) {
//                for (WhiteListInput whiteListInput : filterList) {
//                    LocalDate date = LocalDate.parse(whiteListInput.getRejectDate(), formatter);
//                    Long daysBetween = ChronoUnit.DAYS.between(date, now);
//                    // 判断被拒绝时间
//                    if (daysBetween > 18) {
//                        whiteListInput.setStatus(2);
//                    } else {
//                        // 数据库重复值查询
//                        List<WhiteListInput> whiteListInputs = whiteListInputService.listByPlateAndDate(whiteListInput.getPlateNumber(), whiteListInput.getRejectDate());
//                        if (whiteListInputs.size() > 0) {
//                            whiteListInput.setStatus(0);
//                        } else {
//                            ShortDistanceParam shortDistanceParam = new ShortDistanceParam();
//                            shortDistanceParam.setPlateNumber(whiteListInput.getPlateNumber());
//                            shortDistanceParam.setBeginTime(whiteListInput.getRejectTime());
//                            ShortDistance shortDistance = shortDistanceService.getByPlateAndDate(shortDistanceParam);
//                            // 订单条件判断
//                            if (shortDistance == null || shortDistance.getLeaveTime() == null) {
//                                whiteListInput.setStatus(3);
//                            } else {
//                                Long beginTime = whiteListInput.getOrderBeginTime().getTime();
//                                Long beforeTime = shortDistance.getLeaveTime().getTime() - settingList.get(0).getBeforeOrderTimeLimit() * 60 * 1000;
//                                Long afterTime = shortDistance.getLeaveTime().getTime() + settingList.get(0).getAfterOrderTimeLimit() * 60 * 1000;
//                                if (beginTime.compareTo(beforeTime) < 0 || beginTime.compareTo(afterTime) > 0) {
//                                    whiteListInput.setStatus(3);
//                                } else {
//                                    // 订单里程判断
//                                    BigDecimal orderMileage = new BigDecimal(whiteListInput.getOrderMileage());
//                                    if (orderMileage.compareTo(new BigDecimal(settingList.get(0).getOrderDistanceLimit())) > 0) {
//                                        whiteListInput.setStatus(4);
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//            }
            for (WhiteListInput input : whiteListInputDtos) {
                if (!StringUtils.isEmpty(input.getPlateNumber())) {
                    // 白名单保存入库
                    WhiteList entity = new WhiteList();
                    entity.setPlateNumber(input.getPlateNumber());
                    entity.setDiscountNum(1);
                    entity.setEffectiveDate(new Date(new Date().getTime() + 24 * 60 * 60 * 1000));
                    LocalDate expire = now.plusDays(3);
                    String expireStr = formatter.format(expire) + " 23:59:59";
                    entity.setExpireTime(sdf.parse(expireStr));
                    entity.setReasonType(1);
                    entity.setExchange(0);
                    entity.setCreateUser(login.getUserName());
                    entity.setUpdateUser(login.getUserName());
                    entity.setCreateTime(new Date());
                    entity.setUpdateTime(new Date());
                    whiteListService.insert(entity);
                    //input.setStatus(1);
              }
                whiteListInputService.insert(input);
            }
            return RestResult.ok();
        } catch (Exception e) {
            return RestResult.error(e.getMessage());
        }
    }
}
